<template>
  <el-dialog
    :title="dialogObj.title"
    append-to-body
    :visible.sync="dialogObj.show"
    :close-on-click-modal="false"
    width="60%"
    class="abow_dialog"
  >
    <el-form
      ref="form"
      status-icon
      :model="form"
      label-width="140px"
      :rules="rules"
      :disabled="dialogObj.view == true"
      v-if="dialogObj.show"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称：" prop="productName">
            <el-input
              v-model="form.productName"
              style="width:200px;"
              :disabled="dialogObj.form.isDraft != 1"
              :placeholder="placeholderTips.productName"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品简介：" prop="description">
            <el-input
              v-model="form.description"
              style="width:200px;"
              :placeholder="placeholderTips.description"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品分类：" prop="categoryId">
            <el-select
              v-model="form.categoryId"
              placeholder="请选择类型"
              size="mini"
              :disabled="dialogObj.form.isDraft != 1"
            >
              <el-option
                v-for="(data, index) in prouductSelect"
                :key="index"
                :label="data.categoryName"
                :value="data.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品价格(元)：" prop="currentPrice">
            <el-input-number
              v-model="form.currentPrice"
              style="width:200px;"
              :disabled="dialogObj.form.isDraft != 1"
              :placeholder="placeholderTips.currentPrice"
              size="mini"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="默认库存（个）：" prop="stock">
            <el-input-number
              v-model="form.stock"
              style="width:200px;"
              :disabled="dialogObj.form.isDraft != 1"
              :placeholder="placeholderTips.stock"
              size="mini"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="打包费（元）：" prop="packingCharge">
            <el-input-number
              v-model="form.packingCharge"
              style="width:200px;"
              :disabled="dialogObj.form.isDraft != 1"
              :placeholder="placeholderTips.packingCharge"
              size="mini"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品图：" prop="imgUrl">
            <upload-picture
              :imageValue="form.imgUrl"
              @handleSuccess="handleSuccess"
            >
            </upload-picture>
            <span style="color:red;font-size:12px">推荐尺寸： 264*255</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品详情图：" prop="detailImg">
            <upload-picture
              :imageValue="form.detailImg"
              @handleSuccess="handleSuccessDetail"
            >
            </upload-picture>
            <span style="color:red;font-size:12px">推荐尺寸： 1065*552</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序码：" prop="sort">
            <el-input
              v-model="form.sort"
              style="width:200px;"
              :placeholder="placeholderTips.sort"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="限购数量：" prop="purchaseLimit">
            <el-input
              v-model="form.purchaseLimit"
              style="width:200px;"
              :placeholder="placeholderTips.purchaseLimit"
              size="mini"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="楼层：" prop="venueFloor" v-if="!isHaveFlorr">
        <el-radio-group v-model="form.venueFloor">
          <el-radio
            v-for="(item, index) in floorArr"
            :key="index"
            :label="item.id"
            >{{ item.value }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上架时间：">
        <el-radio-group v-model="onTime">
          <el-radio :label="1">立即上架</el-radio>
          <el-radio :label="2">指定时间</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="指定时间：" prop="shelfTime" v-if="onTime == 2">
        <el-date-picker
          v-model="form.shelfTime"
          format="yyyy-MM-dd HH"
          type="datetime"
          placeholder="选择日期时间"
          size="mini"
          :picker-options="onPickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下架时间：">
        <el-radio-group v-model="offTime">
          <el-radio :label="1">指定时间</el-radio>
          <el-radio :label="2">长期不下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="指定时间：" prop="offShelfTime" v-if="offTime == 1">
        <el-date-picker
          v-model="form.offShelfTime"
          format="yyyy-MM-dd HH"
          type="datetime"
          placeholder="选择日期时间"
          size="mini"
          :picker-options="offPickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="详情描述：">
        <image-text :tableData="tableData" @handleTableDate="handleTableDate">
        </image-text>
      </el-form-item>
    </el-form>
    <div class="operate-footer">
      <el-button
        type="primary"
        @click="sub(1)"
        size="mini"
        v-if="dialogObj.form.isDraft != 4 && dialogObj.view != true"
        >保存为草稿</el-button
      >
      <el-button
        type="primary"
        @click="sub(2)"
        size="mini"
        v-if="dialogObj.view != true"
        >确 定</el-button
      >
      <el-button
        @click="dialogObj.show = false"
        size="mini"
        v-if="dialogObj.view != true"
        >取 消</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import { FLOORARR2 } from "@u/wordbook";
import { _debounce } from "@u/debounce";
import {
  placeholderTips,
  validateString,
  validateNumberII,
  validateNumber,
  validateNumEmpty,
  validateStringSpecial,
  validateTemplate,
  validateTemplateFloor,
  validateTemplatePicture,
  validateTemplateTime,
  validateNumInt
} from "@u/validate";
import imageText from "@c/imageText";
import uploadPicture from "@c/uploadPicture";
import {
  getProductSelectApi,
  updateGoodsInfoApi,
  addGoodsInfoApi
} from "@s/api";
import timeFormat from "@u/timeFormat";
import Cookie from "@u/cookie";
export default {
  name: "dialogCom",
  props: ["dialogObj"],
  components: {
    imageText,
    uploadPicture
  },
  data() {
    return {
      floorArr: FLOORARR2,
      placeholderTips: placeholderTips,
      onTime: 1, //1 立即上架  2 指定时间
      offTime: 2, //1 指定时间  2 长期不下架
      goodStatus: "", // 1 草稿  2 非草稿
      tableData: [
        {
          imageUrl: "",
          description: ""
        }
      ],
      prouductSelect: [],
      isHaveFlorr:
        JSON.parse(localStorage.getItem("mb_userInfo")).venueFloor == 0
          ? ""
          : JSON.parse(localStorage.getItem("mb_userInfo")).venueFloor, // 是否有楼层
      // isHaveFlorr: 1, // 是否有楼层
      form: {
        productorCategory: 1, // 1 餐饮
        categoryId: "", // 商品分类 id
        currentPrice: "", // 价格
        description: "", // 商品简介
        imgUrl: "", // 商品图片
        detailImg: "", // 商品详情图
        detail: "", // 商品详情
        isDraft: "", // 商品状态 1草稿 2 待上架 3 上架中 4 已下架
        offShelfTime: "", // 下架时间
        packingCharge: "", // 打包费
        productName: "", // 商品名字
        purchaseLimit: "", // 限购数量
        shelfTime: "", // 上架时间
        sort: "", // 排序码
        stock: "", //  库存
        venueFloor: "" // 楼层
      },
      // 上架日期限制
      onPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // 下架日期限制
      offPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },
      rules: {
        sort: [{ validator: validateNumEmpty }],
        categoryId: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { validator: validateTemplate }
        ],
        currentPrice: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { validator: validateNumber }
        ],
        description: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { validator: validateString }
        ],
        imgUrl: [
          { required: true, message: "请上传图片", trigger: "change" },
          { validator: validateTemplatePicture }
        ],
        detailImg: [
          { required: true, message: "请上传图片", trigger: "change" },
          { validator: validateTemplatePicture }
        ],
        offShelfTime: [
          { required: true, message: "请选择时间", trigger: "blur" },
          { validator: validateTemplateTime }
        ],
        packingCharge: [{ validator: validateNumberII }],
        purchaseLimit: [{ validator: validateNumEmpty }],
        venueFloor: [
          { required: true, message: "请选择楼层", trigger: "blur" },
          { validator: validateTemplateFloor }
        ],
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { validator: validateStringSpecial }
        ],
        stock: [
          { required: true, message: "请输入库存", trigger: "blur" },
          { validator: validateNumInt }
        ],
        shelfTime: [
          { required: true, message: "请选择时间", trigger: "blur" },
          { validator: validateTemplateTime }
        ]
      }
    };
  },
  mounted() {},
  methods: {
    initDialog() {
      if (this.dialogObj.id) {
        this.form.categoryId = this.dialogObj.form.categoryId;
        this.form.currentPrice = this.dialogObj.form.currentPrice;
        this.form.description = this.dialogObj.form.description;
        this.form.imgUrl = this.dialogObj.form.imgUrl;
        this.form.detailImg = this.dialogObj.form.detailImg;
        if (this.dialogObj.form.detail) {
          this.tableData = JSON.parse(this.dialogObj.form.detail);
        } else {
          this.tableData = {
            imageUrl: "",
            description: ""
          };
        }
        this.form.detail = "";
        this.form.isDraft = this.dialogObj.form.isDraft;
        this.form.packingCharge = this.dialogObj.form.packingCharge;
        this.form.productName = this.dialogObj.form.productName;
        this.form.purchaseLimit = this.dialogObj.form.purchaseLimit;

        this.form.sort = this.dialogObj.form.sort;
        this.form.stock = this.dialogObj.form.stock;
        this.form.venueFloor = Number(this.dialogObj.form.venueFloor);
        if (this.dialogObj.form.offShelfTime) {
          this.form.offShelfTime = this.dialogObj.form.offShelfTime;
          this.offTime = 1; //1 指定时间  2 长期不下架
        } else {
          this.form.offShelfTime = "";
          this.offTime = 2;
        }
        if (this.dialogObj.form.shelfTime) {
          this.form.shelfTime = this.dialogObj.form.shelfTime;
          this.onTime = 2; //1 立即上架  2 指定时间
        } else {
          this.onTime = 1;
          this.form.shelfTime = "";
        }
      } else {
        this.onTime = 1; //1 立即上架  2 指定时间
        this.offTime = 2; //1 指定时间  2 长期不下架
        this.form.offShelfTime = "";
        this.form.shelfTime = "";
        this.tableData = [
          {
            imageUrl: "",
            description: ""
          }
        ];
        this.form.categoryId = "";
        this.form.currentPrice = "";
        this.form.description = "";
        this.form.imgUrl = "";
        this.form.detailImg = "";
        this.form.detail = "";
        this.form.detailImg = "";
        this.form.isDraft = "";

        this.form.packingCharge = "";
        this.form.productName = "";
        this.form.purchaseLimit = "";

        this.form.sort = "";
        this.form.stock = "";
        let venueFloorNum =
          JSON.parse(localStorage.getItem("mb_userInfo")).venueFloor || "";
        if (Number(venueFloorNum) !== 0) {
          this.form.venueFloor = Number(
            JSON.parse(localStorage.getItem("mb_userInfo")).venueFloor
          );
        } else if (Number(venueFloorNum) == 0) {
          this.form.venueFloor = "";
        }
      }
    },
    productSelect() {
      var json = {
        categoryType: 1 // 1 餐饮
      };
      getProductSelectApi(json).then(res => {
        this.prouductSelect = res;
      });
    },
    handleTableDate() {},
    // 图片上传
    handleSuccess(val) {
      this.form.imgUrl = val;
    },
    handleSuccessDetail(val) {
      this.form.detailImg = val;
    },
    sub: _debounce(function(val) {
      this.goodStatus = val;
      this.form.detail = JSON.stringify(this.tableData);
      if (!this.form.sort) {
        this.form.sort = 999; // 默认排序码
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (
            this.form.shelfTime &&
            this.form.offShelfTime &&
            this.offTime == 1 &&
            this.onTime == 2
          ) {
            var shelfTime = null;
            var offShelfTime = null;
            if (this.dialogObj.id) {
              shelfTime = new Date(this.form.shelfTime);
              offShelfTime = new Date(this.form.offShelfTime);
            } else {
              shelfTime = this.form.shelfTime;
              offShelfTime = this.form.offShelfTime;
            }
            // this.dialogObj.show = false;
            if (shelfTime > offShelfTime) {
              this.$message({
                type: "warning",
                message: "下架时间必须大于上架时间！"
              });
            } else {
              if (this.dialogObj.id) {
                this.updateSub();
              } else {
                this.addSub();
              }
            }
          } else {
            if (this.dialogObj.id) {
              this.updateSub();
            } else {
              this.addSub();
            }
          }
        } else {
          this.$message({
            type: "warning",
            message: "必选项未填完！"
          });
        }
      });
    }),
    addSub() {
      let json = JSON.parse(JSON.stringify(this.form));
      if (this.goodStatus == 1) {
        json.isDraft = 1; // 草稿
      }
      if (this.onTime == 1) {
        // 立即上架
        json.shelfTime = timeFormat.hoursTime(new Date());
        if (this.goodStatus == 2) {
          json.isDraft = 3; // 上架中
        }
      } else {
        json.shelfTime = timeFormat.hoursTime(this.form.shelfTime);
        if (this.goodStatus == 2) {
          json.isDraft = 2; // 待上架
        }
      }
      if (this.offTime == 2) {
        // 长期不下架
        json.offShelfTime = "";
      } else {
        json.offShelfTime = timeFormat.hoursTime(this.form.offShelfTime);
      }
      addGoodsInfoApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "添加成功！"
        });
      });
    },
    updateSub() {
      let json = JSON.parse(JSON.stringify(this.form));
      if (this.goodStatus == 1) {
        json.isDraft = 1; // 草稿
      }
      if (this.onTime == 1) {
        // 立即上架
        json.shelfTime = timeFormat.hoursTime(new Date());
        if (this.goodStatus == 2) {
          json.isDraft = 3; // 上架中
        }
      } else {
        json.shelfTime = timeFormat.hoursTime(this.form.shelfTime);
        if (this.goodStatus == 2) {
          json.isDraft = 2; // 待上架
        }
      }
      if (this.offTime == 2) {
        // 长期不下架
        json.offShelfTime = "";
      } else {
        json.offShelfTime = timeFormat.hoursTime(this.form.offShelfTime);
      }
      json.id = this.dialogObj.id;
      updateGoodsInfoApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "修改成功！"
        });
      });
    }
  },
  watch: {
    "dialogObj.show"(val) {
      if (val) {
        this.initDialog();
        this.productSelect();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.operate-footer {
  text-align: center;
}
</style>
